<template>
  <div class="transaction-history">
    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <a-row :gutter="16" >
        <a-col :span="2.5">
          <a-select
            v-model:value="filters.type"
            placeholder="交易类型"
            allow-clear
            @change="handleFilterChange"
          >
            <!-- <a-select-option value="recharge">充值</a-select-option> -->
            <!-- <a-select-option value="withdraw">提现</a-select-option> -->
            <a-select-option value="rent_income">出租收入</a-select-option>
            <a-select-option value="rent_expense">租赁支出</a-select-option>
            <!-- <a-select-option value="deposit_pay">押金支付</a-select-option> -->
            <!-- <a-select-option value="deposit_refund">押金退还</a-select-option> -->
            <a-select-option value="extra_fee">额外费用</a-select-option>
            <!-- <a-select-option value="commission">平台佣金</a-select-option> -->
            <a-select-option value="invite_commission">邀请佣金</a-select-option>
            <a-select-option value="refund">退款</a-select-option>
            <a-select-option value="adjustment">余额调整</a-select-option>
          </a-select>
        </a-col>
        <!-- <a-col :span="6">
          <a-select
            v-model:value="filters.status"
            placeholder="交易状态"
            allow-clear
            @change="handleFilterChange"
          >
            <a-select-option value="success">成功</a-select-option>
            <a-select-option value="pending">处理中</a-select-option>
            <a-select-option value="failed">失败</a-select-option>
            <a-select-option value="cancelled">已取消</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="8">
          <a-range-picker
            v-model:value="dateRange"
            @change="handleDateChange"
            placeholder="['开始日期', '结束日期']"
          />
        </a-col> -->
          <a-button type="primary" @click="refreshData" :loading="loading">
            刷新
          </a-button>
      </a-row>
    </div>

    <!-- 交易记录表格 -->
    <div class="table-section">
      <!-- PC端表格 -->
      <a-table
        :columns="columns"
        :data-source="transactions"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="_id"
        size="middle"
        class="desktop-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'transactionNumber'">
            <span class="transaction-number">{{ record.transactionNumber }}</span>
          </template>
          
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'amount'">
            <span :class="['amount', record.amount >= 0 ? 'income' : 'expense']">
              {{ record.amount >= 0 ? '+' : '' }}{{ formatPrice(record.amount) }}
            </span>
          </template>
          
          <template v-if="column.key === 'balanceAfter'">
            <span class="balance-after">¥{{ formatPrice(record.balanceAfter) }}</span>
          </template>
          
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'createdAt'">
            <span>{{ formatDate(record.createdAt) }}</span>
          </template>
          
          <template v-if="column.key === 'action'">
            <a-button size="small" @click="viewDetail(record)">
              查看详情
            </a-button>
          </template>
        </template>
      </a-table>
      
      <!-- 移动端卡片布局 -->
      <div class="mobile-transaction-cards">
        <div 
          v-for="record in transactions" 
          :key="record._id" 
          class="transaction-card"
          @click="viewDetail(record)"
        >
          <div class="transaction-card-header">
            <div class="transaction-type">
              <a-tag :color="getTypeColor(record.type)">
                {{ getTypeText(record.type) }}
              </a-tag>
            </div>
            <div class="transaction-status">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </div>
          </div>
          
          <div class="transaction-card-content">
            <div class="amount-row">
              <span class="amount-label">交易金额</span>
              <span :class="['amount-value', record.amount >= 0 ? 'income' : 'expense']">
                {{ record.amount >= 0 ? '+' : '' }}{{ formatPrice(record.amount) }}
              </span>
            </div>
            
            <div class="balance-row">
              <span class="balance-label">交易后余额</span>
              <span class="balance-value">¥{{ formatPrice(record.balanceAfter) }}</span>
            </div>
            
            <div class="transaction-number-row">
              <span class="number-label">流水号</span>
              <span class="number-value">{{ record.transactionNumber }}</span>
            </div>
            
            <div class="transaction-time">
              {{ formatDate(record.createdAt) }}
            </div>
          </div>
        </div>
      </div>
      
      <!-- 移动端分页 -->
      <div class="mobile-pagination">
        <a-pagination
          v-model:current="pagination.current"
          v-model:pageSize="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="false"
          :show-quick-jumper="false"
          simple
          @change="handleTableChange"
        />
      </div>
    </div>

    <!-- 交易详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="交易详情"
      width="700px"
      :footer="null"
    >
      <div v-if="selectedTransaction" class="transaction-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="流水号">
            {{ selectedTransaction.transactionNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="交易类型">
            <a-tag :color="getTypeColor(selectedTransaction.type)">
              {{ getTypeText(selectedTransaction.type) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="交易金额">
            <span :class="['amount', selectedTransaction.amount >= 0 ? 'income' : 'expense']">
              {{ selectedTransaction.amount >= 0 ? '+' : '' }}{{ formatPrice(selectedTransaction.amount) }}
            </span>
          </a-descriptions-item>
          <a-descriptions-item label="交易后余额">
            ¥{{ formatPrice(selectedTransaction.balanceAfter) }}
          </a-descriptions-item>
          <a-descriptions-item label="交易状态">
            <a-tag :color="getStatusColor(selectedTransaction.status)">
              {{ getStatusText(selectedTransaction.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="交易时间">
            {{ formatDate(selectedTransaction.createdAt) }}
          </a-descriptions-item>
          <a-descriptions-item label="交易描述" :span="2">
            {{ selectedTransaction.description }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedTransaction.remark" label="备注" :span="2">
            {{ selectedTransaction.remark }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedTransaction.order" label="关联订单" :span="2">
            {{ selectedTransaction.order.orderNumber }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedTransaction.account" label="关联账号" :span="2">
            {{ selectedTransaction.account.number }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import transactionAPI from '~/api/transaction'

// Props
const props = defineProps({
  // 可以添加一些配置项
})

// Emits
const emit = defineEmits(['transaction-updated'])

// 响应式数据
const loading = ref(false)
const transactions = ref([])
const currentBalance = ref(0)
const totalIncome = ref(0)
const totalExpense = ref(0)
const detailVisible = ref(false)
const selectedTransaction = ref(null)
const dateRange = ref(null)

// 筛选条件
const filters = reactive({
  type: null,
  status: null,
  startDate: null,
  endDate: null
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
  pageSizeOptions: ['10', '20', '50', '100']
})

// 表格列定义
const columns = [
  {
    title: '流水号',
    dataIndex: 'transactionNumber',
    key: 'transactionNumber',
    width: 150,
    ellipsis: true
  },
  {
    title: '交易类型',
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: '交易金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 120
  },
  {
    title: '交易后余额',
    dataIndex: 'balanceAfter',
    key: 'balanceAfter',
    width: 120
  },
  {
    title: '交易状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '交易时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 100,
    fixed: 'right'
  }
]

// 获取交易记录
const fetchTransactions = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...filters
    }
    
    const res = await transactionAPI.getUserTransactions(params)
    
    if (res.code === 200) {
      transactions.value = res.data.list
      pagination.total = res.data.total
    } else {
      message.error(res.message || '获取交易记录失败')
    }
  } catch (error) {
    console.error('获取交易记录失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取余额统计
const fetchBalanceStats = async () => {
  try {
    const params = {}
    if (filters.startDate) params.startDate = filters.startDate
    if (filters.endDate) params.endDate = filters.endDate
    
    const res = await transactionAPI.getBalanceStats(params)
    
    if (res.code === 200) {
      currentBalance.value = res.data.currentBalance
      totalIncome.value = res.data.totalIncome
      totalExpense.value = res.data.totalExpense
    }
  } catch (error) {
    console.error('获取余额统计失败:', error)
  }
}

// 刷新数据
const refreshData = () => {
  fetchTransactions()
  // fetchBalanceStats()
}

// 筛选条件变化
const handleFilterChange = () => {
  pagination.current = 1
  fetchTransactions()
  // fetchBalanceStats()
}

// 日期范围变化
const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    filters.startDate = dates[0].format('YYYY-MM-DD')
    filters.endDate = dates[1].format('YYYY-MM-DD')
  } else {
    filters.startDate = null
    filters.endDate = null
  }
  handleFilterChange()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchTransactions()
}

// 查看详情
const viewDetail = (transaction) => {
  selectedTransaction.value = transaction
  detailVisible.value = true
}

// 格式化函数
const formatPrice = (price) => {
  return (price || 0).toFixed(2)
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取交易类型颜色
const getTypeColor = (type) => {
  const colorMap = {
    'recharge': 'green',
    'withdraw': 'red',
    'rent_income': 'blue',
    'rent_expense': 'orange',
    'deposit_pay': 'purple',
    'deposit_refund': 'cyan',
    'extra_fee': 'volcano',
    'commission': 'magenta',
    'invite_commission': 'geekblue',
    'refund': 'lime',
    'adjustment': 'gold'
  }
  return colorMap[type] || 'default'
}

// 获取交易类型文本
const getTypeText = (type) => {
  const textMap = {
    'recharge': '充值',
    'withdraw': '提现',
    'rent_income': '出租收入',
    'rent_expense': '租赁支出',
    'deposit_pay': '押金支付',
    'deposit_refund': '押金退还',
    'extra_fee': '额外费用',
    'commission': '平台佣金',
    'invite_commission': '佣金收入',
    'refund': '退款',
    'adjustment': '余额调整'
  }
  return textMap[type] || type
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    'pending': 'orange',
    'success': 'green',
    'failed': 'red',
    'cancelled': 'default',
    'audit_pending': 'blue',
    'audit_approved': 'green',
    'audit_rejected': 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '处理中',
    'success': '成功',
    'failed': '失败',
    'cancelled': '已取消',
    'audit_pending': '待审核',
    'audit_approved': '审核通过',
    'audit_rejected': '审核拒绝'
  }
  return textMap[status] || status
}

// 初始化
onMounted(() => {
  fetchTransactions()
  // fetchBalanceStats()
})
</script>

<style scoped lang="scss">
.transaction-history {
  .stats-cards {
    margin-bottom: 24px;

    .stat-card {
      .stat-item {
        text-align: center;

        .stat-label {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: 600;

          &.balance {
            color: #1890ff;
          }

          &.income {
            color: #52c41a;
          }

          &.expense {
            color: #f5222d;
          }
        }
      }
    }
  }

  .filter-section {
    background: white;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .table-section {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .transaction-number {
      font-family: monospace;
      font-size: 12px;
    }

    .amount {
      font-weight: 600;

      &.income {
        color: #52c41a;
      }

      &.expense {
        color: #f5222d;
      }
    }

    .balance-after {
      font-weight: 500;
      color: #1890ff;
    }
  }

  .transaction-detail {
    .amount {
      font-weight: 600;

      &.income {
        color: #52c41a;
      }

      &.expense {
        color: #f5222d;
      }
    }
  }

  :deep(.ant-table) {
    .ant-table-thead > tr > th {
      background-color: #fafafa;
      font-weight: 500;
    }

    .ant-table-tbody > tr > td {
      padding: 12px 16px;
    }
  }
  
  // 默认隐藏移动端元素
  .mobile-transaction-cards,
  .mobile-pagination {
    display: none;
  }
  
  .desktop-table {
    display: table;
  }
}

// 移动端适配
@media (max-width: 768px) {
  .transaction-history {
    * {
      box-sizing: border-box;
    }
    .filter-section {
      padding: 12px;
      margin-bottom: 12px;
      
      .ant-row {
        flex-direction: column;
        
        .ant-col {
          width: 100% !important;
          margin-bottom: 8px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .ant-select,
          .ant-btn {
            width: 100%;
            height: 44px;
          }
          
          .ant-btn {
            font-size: 14px;
          }
        }
      }
    }

    .table-section {
      padding: 0;
      
      // 隐藏PC端表格
      .desktop-table {
        display: none !important;
      }
      
      // 显示移动端卡片
      .mobile-transaction-cards {
        display: block;
        padding: 12px;
        
        .transaction-card {
          background: #fff;
          border: 1px solid #e8e8e8;
          border-radius: 8px;
          margin-bottom: 12px;
          cursor: pointer;
          overflow: hidden;
          transition: all 0.3s ease;
          
          &:hover {
            border-color: #1890ff;
            box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
          }
          
          .transaction-card-header {
            background: #f8f9fa;
            padding: 12px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e8e8e8;
            
            .transaction-type .ant-tag {
              margin: 0;
              font-size: 11px;
              padding: 2px 8px;
            }
            
            .transaction-status .ant-tag {
              margin: 0;
              font-size: 11px;
              padding: 2px 8px;
            }
          }
          
          .transaction-card-content {
            padding: 12px 16px;
            
            .amount-row,
            .balance-row,
            .transaction-number-row {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;
              
              &:last-of-type {
                margin-bottom: 12px;
              }
            }
            
            .amount-label,
            .balance-label,
            .number-label {
              font-size: 13px;
              color: #666;
              font-weight: 500;
            }
            
            .amount-value {
              font-size: 15px;
              font-weight: 600;
              
              &.income {
                color: #52c41a;
              }
              
              &.expense {
                color: #f5222d;
              }
            }
            
            .balance-value {
              font-size: 14px;
              font-weight: 600;
              color: #1890ff;
            }
            
            .number-value {
              font-size: 12px;
              color: #333;
              font-family: monospace;
              background: #f5f5f5;
              padding: 2px 6px;
              border-radius: 4px;
            }
            
            .transaction-time {
              font-size: 11px;
              color: #999;
              text-align: center;
              padding-top: 8px;
              border-top: 1px solid #f5f5f5;
            }
          }
        }
      }
      
      // 显示移动端分页
      .mobile-pagination {
        display: flex;
        justify-content: center;
        padding: 16px;
        background: #fff;
        border-top: 1px solid #e8e8e8;
        
        :deep(.ant-pagination) {
          .ant-pagination-prev,
          .ant-pagination-next {
            height: 36px;
            line-height: 36px;
            min-width: 36px;
          }
          
          .ant-pagination-item {
            height: 36px;
            line-height: 36px;
            min-width: 36px;
          }
        }
      }
    }
  }
}

// 交易详情弹窗移动端适配
@media (max-width: 768px) {
  :deep(.ant-modal) {
    margin: 16px;
    max-width: calc(100vw - 32px);
    
    .ant-modal-content {
      .ant-modal-header {
        padding: 16px;
        border-bottom: 1px solid #e8e8e8;
        
        .ant-modal-title {
          font-size: 16px;
        }
      }
      
      .ant-modal-body {
        padding: 16px;
        max-height: 70vh;
        overflow-y: auto;
        
        .transaction-detail {
          :deep(.ant-descriptions) {
            .ant-descriptions-item {
              padding: 8px 12px;
              
              .ant-descriptions-item-label {
                font-size: 13px;
                font-weight: 500;
              }
              
              .ant-descriptions-item-content {
                font-size: 13px;
                
                .amount {
                  font-weight: 600;
                  
                  &.income {
                    color: #52c41a;
                  }
                  
                  &.expense {
                    color: #f5222d;
                  }
                }
                
                .ant-tag {
                  font-size: 11px;
                  padding: 1px 6px;
                }
              }
            }
          }
        }
      }
      
      .ant-modal-close {
        top: 8px;
        right: 8px;
      }
    }
  }
}

// 超小屏幕适配
@media (max-width: 480px) {
  .transaction-history {
    * {
      box-sizing: border-box;
    }
    .filter-section {
      padding: 8px;
      
      .ant-row .ant-col {
        .ant-select,
        .ant-btn {
          height: 40px;
          font-size: 13px;
        }
      }
    }
    
    .table-section {
      .mobile-transaction-cards {
        padding: 8px;
        
        .transaction-card {
          margin-bottom: 8px;
          border-radius: 6px;
          
          .transaction-card-header {
            padding: 10px 12px;
            
            .transaction-type .ant-tag,
            .transaction-status .ant-tag {
              font-size: 10px;
              padding: 1px 6px;
            }
          }
          
          .transaction-card-content {
            padding: 10px 12px;
            
            .amount-row,
            .balance-row,
            .transaction-number-row {
              margin-bottom: 6px;
            }
            
            .amount-label,
            .balance-label,
            .number-label {
              font-size: 12px;
            }
            
            .amount-value {
              font-size: 14px;
            }
            
            .balance-value {
              font-size: 13px;
            }
            
            .number-value {
              font-size: 11px;
            }
            
            .transaction-time {
              font-size: 10px;
              padding-top: 6px;
            }
          }
        }
      }
      
      .mobile-pagination {
        padding: 12px;
      }
    }
  }
}
</style> 